#include <iostream>
#include <memory>
#include <cassert>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <vector>

#include "HttpServer.hpp"

#define ROOT "./wwwroot"
#define HOMEPAGE "index.html"

void cutString(std::string s, const std::string &sep, std::vector<std::string> *out)
{
    std::size_t start = 0;
    while(start < s.size())
    {
        auto pos = s.find(sep, start);
        if(pos == std::string::npos) break;
        std::string sub = s.substr(start, pos - start);
        out->push_back(sub);
        start += sub.size();
        start += sep.size();
    }
    if(start < s.size()) out->push_back(s.substr(start));
}

void HandlerHttpRequest(int sockfd)
{
    char buffer[10240];
    ssize_t s = recv(sockfd, buffer, sizeof(buffer)-1, 0);
    if(s > 0)
    {
        buffer[s] = 0;
        std::cout << buffer << std::endl;
        std::cout << "------------------" << std::endl;
    }

    std::vector<std::string> vline;
    cutString(buffer, "\n", &vline);

    std::vector<std::string> vblock;
    cutString(vline[0], " ", &vblock);

    std::string file = vblock[1];
    std::string target = ROOT;

    if(file == "/") file = "/index.html";
    target += file;
    std::cout << target << std::endl;

    std::string content;
    std::ifstream in(target);
    if(in.is_open())
    {
        std::string line;
        while(std::getline(in, line))
        {
            content += line;
        }
        in.close();
    }

    std::string HttpResponse;
    if(content.empty())
    {
        HttpResponse = "HTTP/1.1 301 Moved Permanently\r\n";
        HttpResponse += "Location: http://43.138.129.45:8081/index.html\r\n";
    }
    else
    {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
        HttpResponse += ("Content-Type: text/html\r\n");
        HttpResponse += ("Content-Length: " + std::to_string(content.size()) + "\r\n");
        HttpResponse += "Set-Cookie: 这是一个cookie\r\n";
    }
    HttpResponse += "\r\n";
    HttpResponse += content;
    send(sockfd, HttpResponse.c_str(), HttpResponse.size(), 0);
}

void Usage(std::string proc)
{
    std::cout << "\nUsage: " << proc <<  " port\n" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::unique_ptr<HttpServer> httpsvr(new HttpServer(atoi(argv[1]), HandlerHttpRequest));
    httpsvr->start();
    return 0;
}